/**
 * 权限守卫
 * 作者：GodMainCode
 * 创建时间：2024-01-17
 * 修改时间：2024-01-17
 * 修改人：GodMainCode
 */

import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { PERMISSIONS_KEY } from '../decorators/permissions.decorator';
import { UserService } from '../../user/user.service';

@Injectable()
export class PermissionsGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private userService: UserService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredPermissions = this.reflector.getAllAndOverride<string[]>(
      PERMISSIONS_KEY,
      [context.getHandler(), context.getClass()],
    );

    if (!requiredPermissions) {
      return true;
    }

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    if (!user) {
      throw new UnauthorizedException('未登录');
    }

    const userWithRoles = await this.userService.findOne(user.id);
    const userPermissions = new Set<string>();

    // 收集用户所有角色的权限
    for (const role of userWithRoles.roles) {
      for (const permission of role.permissions) {
        userPermissions.add(permission.code);
      }
    }

    // 检查是否拥有所需权限
    const hasPermission = requiredPermissions.every(permission => 
      userPermissions.has(permission)
    );

    if (!hasPermission) {
      throw new UnauthorizedException('权限不足');
    }

    return true;
  }
} 